package connections;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import main.Client;
import main.UserInfo;
import message.StartComunication;
import message.StartSync;

/**
 * register to the server for the next conversation 
 * @author ran,barak
 *
 */
public class RegisterToServer implements Runnable{
	private URL url;
	private URLConnection conn;
	private Client client;
	
	/**
	 * Ctor of RegisterToServer 
	 * @param client
	 */
	public RegisterToServer(Client client) {
		this.client=client;
	}
	
	/**
	 * open connection to the server by http 
	 */
	public void run(){
		// get the userInfo
		UserInfo info = UserInfo.getInstance();
		try {
			// make url connection
			url = new URL("http://localhost:12345/");
			conn = url.openConnection();
			conn.setAllowUserInteraction(true);
			conn.setDoOutput(true);
			// get output stream
			ObjectOutputStream outputStream = new ObjectOutputStream(conn.getOutputStream());
			// send startComunication
		    outputStream.writeObject(new StartComunication(info.getUserName(), info.getPass(),info.getComputerName()));
		    outputStream.flush();
		    outputStream.close();
		    // get inputstream
		    ObjectInputStream inputStream = new ObjectInputStream(conn.getInputStream());
		    // Receive message
		    StartComunication s = (StartComunication)inputStream.readObject();
		    if(s.getUserName().compareTo("server")==0 && s.getPass().compareTo("server")==0)
		    	client.addMessage(new StartSync());
		    inputStream.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
